#pragma once

#include <iostream>
#include <sys/types.h>
#include <cstdio>
#include <cerrno>
#include <sys/stat.h>
#include <string>
#include <unistd.h>
#include <fcntl.h>

const std::string comm_path = "./myfifo";

#define Creater 1
#define User 2
#define DefaultFd -1
#define Read O_RDONLY
#define Write O_WRONLY
#define BaseSize 4096

class NamePipe
{
private:
    bool OpenNamePipe(int mode)
    {
        _fd = open(_fifo_path.c_str(), mode);
        if (_fd < 0)
            return false;
        return true;
    }

public:
    NamePipe(const std::string &path = "./myfifo", int who = User)
        : _fifo_path(path), _id(who), _fd(DefaultFd)
    {
        if (_id == Creater)
        {
            int res = mkfifo(_fifo_path.c_str(), 0666);
            if (res == -1)
            {
                perror("mkfifo");
            }
            std::cout << "Creater create the named pipe successfully!" << std::endl;
        }
    }

    bool OpenForRead()
    {
        return OpenNamePipe(Read);
    }
    bool OpenForWrite()
    {
        return OpenNamePipe(Write);
    }

    // 输入型参数 const &
    // 输出型参数 const *
    // 输入输出型参数 const &
    int ReadNamedPipe(std::string *out)
    {
        char buffer[BaseSize];
        int n = read(_fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }
    int WriteNamedPipe(const std::string& in)
    {
        int n = write(_fd, in.c_str(), in.size());
        if (n == -1)
        {
            perror("write");
        }
        return n;
    }

    ~NamePipe()
    {
        if (_id == Creater)
        {
            int res = unlink(_fifo_path.c_str());
            if (res == -1)
            {
                perror("mkfifo");
            }
            std::cout << "Creater free the named pipe successfully!" << std::endl;
        }
        if (_fd != DefaultFd) close(_fd);
    }

private:
    std::string _fifo_path;
    int _id; // 表明使用管道者的身份
    int _fd; // 文件描述符
};
